package com.good.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.good.common.constant.ProductConstant;
import com.good.shopping.product.dao.AttrAttrgroupRelationDao;
import com.good.shopping.product.dao.AttrGroupDao;
import com.good.shopping.product.dao.CategoryDao;
import com.good.shopping.product.entity.AttrAttrgroupRelationEntity;
import com.good.shopping.product.entity.AttrGroupEntity;
import com.good.shopping.product.entity.CategoryEntity;
import com.good.shopping.product.service.CategoryService;
import com.good.shopping.product.vo.AttrGroupRelatinVo;
import com.good.shopping.product.vo.AttrRespVo;
import com.good.shopping.product.vo.AttrVo;
import com.sun.xml.internal.bind.v2.util.CollisionCheckStack;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.good.common.utils.PageUtils;
import com.good.common.utils.Query;

import com.good.shopping.product.dao.AttrDao;
import com.good.shopping.product.entity.AttrEntity;
import com.good.shopping.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    // 属性&属性分组关联
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    // 属性分组
    @Autowired
    AttrGroupDao attrGroupDao;

    // 商品三级分类
    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    // 保存  - 保存关联关系表
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity pojo = new AttrEntity();
        // 为了更方便赋值，可以使用spring提供的BeanUtils.copyProperties()方法赋值
        BeanUtils.copyProperties(attr,pojo);
        // 1 保存基本数据
        this.save(pojo);
        // 2 保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(pojo.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    /**
     *  查询 平台属性 - 规格参数列表数据
     *  attrType 规格参数/销售参数
     *  catelogId 分类id
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        // 属性类型[0-销售属性，1-基本属性，2-既是销售属性又是基本属性]
        Integer typeCode = "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",typeCode);
        // 所属分类 三级分类id
        if (catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }
        // 要搜索的字段
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((item)->{
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> vos = records.stream().map((item) -> {
            AttrRespVo v = new AttrRespVo();
            BeanUtils.copyProperties(item,v);
            // 1 设置分类和分组的名字
            if ("base".equalsIgnoreCase(type)) {
                AttrAttrgroupRelationEntity attrId =
                        relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    v.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            if (categoryEntity != null) {
                v.setCatelogName(categoryEntity.getName());
            }

            return v;
        }).collect(Collectors.toList());
        pageUtils.setList(vos);
        return pageUtils;
    }


    //  查询单条数据 - 父-子-孙 所属分类、分组id都回显出来   增加缓存 #root.args[0] 获取第一个参数值
    @Cacheable(value = "attr",key = "'attrinfo:'+ #root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {

        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        // 属性为基本属性才保存分组信息，不是不保存
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 1 设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation=
                    relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrgroupRelation != null) {
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if (attrGroupEntity != null) {
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 2 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        // 获取三级分类数组
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }
        return  respVo;
    }

    // 修改操作 -
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 1 修改分组关联  （属性&属性分组关联）
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            // 判断，先查询，如果该属性id在关系表没有 - 代表是新增，如果存在就修改。
            Integer count =
                    relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }

        }
    }

    /**
     *  根据分组id查询关联所有属性
     *  属性分组 - 关联 -列表查询
     *     attrgroupId  分组id
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> entities =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        // 根据ids 查询
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        List<AttrEntity> list = (List<AttrEntity>) this.listByIds(attrIds);
        return list;

    }

    /**
     * 属性分组 - 关联 - 批量删除
     *
     * @param vos
     * @return
     */
    @Override
    public void deleteRelation(AttrGroupRelatinVo[] vos) {
        // 数组 转 list
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        // 使用Mapping 进行批量删除
        relationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * 平台属性 - 属性分组 - 关联 - 新建关联 - 查询列表
     * @param attrgroupId 分组id
     * @param params 分页信息
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1 当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        // 所属分类id  ( 当前分组id 查询 该分组下的全部的属性 )
        Long catelogId = attrGroupEntity.getCatelogId();

        // 2 当前分组只能关联别的分组没有引用的属性
        // 2.1 当前分类下的其他分组   ne (不等)
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId);
        //  .ne("attr_group_id",attrgroupId)
        List<AttrGroupEntity> group = attrGroupDao.selectList(wrapper);

        List<Long> attrGroupIds = group.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        // 2.2 这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId =
                relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        //   已经绑定过的属性id集合
        List<Long> attrIds = groupId.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        // 2.3 从当前分类下的所有属性移除这些属性
        //   查询条件  当前的分类下的  不包含 上面的那些已选择的 属性id集合
        QueryWrapper<AttrEntity> wrapper2 = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            wrapper2.notIn("attr_id",attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper2.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper2);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }


    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return  baseMapper.selectSearchAttrIds(attrIds);
    }

}
